package com.mp.approvalreq.servlet;

import com.alibaba.fastjson.JSONObject;
import com.mp.approvalreq.entity.Request;
import com.mp.approvalreq.entity.Template;
import com.mp.approvalreq.service.ReadTemplateServicePrx;
import com.mp.approvalreq.util.ApprovalUtils;
import com.mp.approvalreq.util.ServiceUtils;
import com.mp.user.entity.User;
import com.plusmoney.exception.RpcServerLogicalException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 新建审批模板时,才会调用,如果是修改审批模板生成新的模板,则是调用模板详情
 *
 * @author Administrator
 */
@WebServlet("/getDefaultTemplateDetail")
public class GetDefaultTemplateDetail extends AbstractServlet {

    private static final Logger logger = LoggerFactory.getLogger(GetDefaultTemplateDetail.class);

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        try {
            User user = getReqUser(req);

            if (!ApprovalUtils.isApprovalAdmin(user)) {
                throw new RpcServerLogicalException(1, "无权操作");
            }

            Template template = getTemplate(req);
            check(template);

            ReadTemplateServicePrx readTemplateServicePrx = ServiceUtils.getReadTemplateServicePrx();
            Template templateDetail = readTemplateServicePrx.getDetaultTemplateDetail(template.getTemplateId());

            returnResult(resp, templateDetail);
        } catch (Throwable e) {
            onThrowable(req, resp, e);
        }
    }

    private void returnResult(HttpServletResponse resp, Template templateDetail) throws IOException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result", "0");
        jsonObject.put("res_info", "获得成功");
        jsonObject.put("data", templateDetail);

        logger.info(jsonObject.toJSONString());

        printJson(resp, jsonObject.toJSONString());
    }

    private Template getTemplate(HttpServletRequest req) throws IOException {
        String reqBody = getContent(req);
        logger.info("json参数值 {}", reqBody);

        Template template;
        try {
            template = JSONObject.parseObject(reqBody, Request.class);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new RpcServerLogicalException(1, "审批内容提交失败，请稍候再试");
        }
        return template;
    }


    protected void check(Template template) {
        if (template.getTemplateId() == 0) {
            throw new RpcServerLogicalException(1, "模板参数不正确");
        }
    }

}
